// pages/contract/component/contractDetail.js
const app = getApp()
const network = require("../../../utils/network");
import util, {formatDate} from "../../../utils/util";
import amount from "../../../utils/amount";
import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";

const {
    add
} = require("../../../utils/amount");

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        disabled: {
            type: Boolean,
            value: false
        },
        readonly: {
            type: Boolean,
            value: false
        },
        contractId: {
            type: Number,
            value: -1
        },
        showCloseBtn: {
            type: Boolean,
            value: false
        },
        parentId: {
            type: Number,
            value: null
        }
    },
    async ready() {
        util.showLoading('加载中')
        await this.initCustomer().catch(() => {
            Toast.fail('加载失败')
            util.hideLoading()
        })
        await this.initMediaTypeArr().catch(() => {
            Toast.fail('加载失败')
            util.hideLoading()
        })
        await this.initCompanyArr().catch(() => {
            Toast.fail('加载失败')
            util.hideLoading()
        })
        if (this.properties.contractId !== -1) {
            this.getDetail().catch(() => {
                Toast.fail('加载失败')
                util.hideLoading()
            })
        }
        util.hideLoading()
    },
    /**
     * 组件的初始数据
     */
    data: {
        contractInfo: {
            id: null,
            parent_id: null,
            contract_num: '提交后自动生成合同编号',
            customer_id: null,
            part_a: null,
            part_b_id: null,
            part_b_name: null,
            part_a_contact: null,
            part_b_contact: null,
            bank_account_name: null,
            bank_name: null,
            bank_num: null,
            contract_begin_date: null,
            contract_end_date: null,
            sign_date: null,
            discounted_price: 0,
            discounted_price_big: '零元整',
            contain_tax: false,
            tax_percent: null,
            self_price: 0,
            self_price_big: '零元整',
            proxy_price: 0,
            proxy_price_big: '零元整',
            replace_price: null,
            multi_replace_price: null,
            acceptance_way: null,
            pay_cash_amount: 0,
            pay_cash_amount_big: '零元整',
            displace_amount: 0,
            displace_amount_big: '零元整',
            memo: null,
            other_memo: null,
            mediaDetailList: [],
            attachmentList: [],
            proxyMediaDetailList: [],
            payDetailList: [],
            contractMediaReplacePriceList: [],
            contractProxyMediaReplacePriceList: [],
            // 以下属性为选择的文本信息
            customer_name: '',
            dateRange: ''
        },
        activeNames: ['1', '2'],
        replaceActiveNames: ['1', '2'],
        activeNames2: ['1'],
        activeNames3: ['1'],
        activeNames4: ['1'],
        customer_arr: [],
        part_a_arr: [],
        media_type_arr: [],
        media_type_obj: {},
        company_arr: [],
        params: {
            isMock: false
        },

        defaultChildInfo: {
            '1_1': {
                media_type_id: null,
                media_type_spec_arr: [],
                media_type_name: null,
                media_type_spec_id: null,
                quantity: null,
                duration: null,
                amount: null
            },
            '1_2': {
                proxy_media_type: null,
                media_type_spec: null,
                quantity: null,
                duration: null,
                amount: null
            },
            '2_1': {
                media_type_id: null,
                media_type_name: null,
                replace_price: null
            },
            '2_2': {
                media_type_id: null,
                media_type_name: null,
                replace_price: null
            },
            '3_1': {
                pay_time: null,
                pay_amount: null,
                pay_type: '1'
            }
        },
        currentDate: new Date().getTime(),
        selectCustomerShow: false,
        selectCustomerLoading: true,
        selectPartALoading: true,
        selectCompanyShow: false,
        selectCompanyLoading: true,
        calendarShow: false,
        calendarRangeShow: false,
        type: 1,
        payIndex: -1,
        selectMediaTypeLoading: false,
        showPopupType: 1,
        selectMediaTypeShow: false,
        tmpIndex: -1,
        media_type_spec_arr: [],
        selectMediaTypeSpecShow: false,
        selectMediaTypeSpecLoading: false,
        datetimePickerShow: false,
        date_key: ''
    },
    /**
     * 组件的方法列表
     */
    methods: {
        closePopup() {
            this.triggerEvent('close')
        },
        onChange(e) {
            this.setData({
                activeNames: e.detail
            })
        },
        onReplaceActiveNamesChange(e) {
            this.setData({
                replaceActiveNames: e.detail
            })
        },
        onchange2(e) {
            this.setData({
                activeNames2: e.detail
            })
        },
        onchange3(e) {
            this.setData({
                activeNames3: e.detail
            })
        },
        onchange4(e) {
            this.setData({
                activeNames4: e.detail
            })
        },
        //添加一项
        addOption({
                      currentTarget: {
                          dataset
                      }
                  }) {
            const {
                basic
            } = this._getMTKeyByIndexAndType(dataset);
            const defaultInfo = Object.assign({}, this.data.defaultChildInfo[dataset.cate + '_' + dataset.type], {
                id: util.generateUUID()
            });
            let list = JSON.parse(JSON.stringify(this.data.contractInfo[basic]));
            list.push(defaultInfo)
            this.setData({
                ['contractInfo.' + basic]: list
            })
        },
        //删除一项
        removeOption({
                         currentTarget: {
                             dataset
                         }
                     }) {
            this.selectComponent('.del-confirm-dialog').show(dataset);
        },
        delConfirm({
                       detail
                   }) {
            const {
                basic
            } = this._getMTKeyByIndexAndType(detail);
            console.log(detail);
            let list = JSON.parse(JSON.stringify(this.data.contractInfo[basic]));
            list.splice(detail.index, 1)
            this.setData({
                ['contractInfo.' + basic]: list
            })
        },
        selectCustomerConfirm(e) {
            const that = this
            that.setData({
                'contractInfo.customer_id': e.detail.value.id,
                'contractInfo.customer_name': e.detail.value.name,
                'contractInfo.part_a': null
            }, function () {
                that.initPartAArr();
                that.selectComponent('.part-a-picker').reset();
            })
        },
        selectPartAConfirm(e) {
            const that = this
            that.setData({
                'contractInfo.part_a': e.detail.value.name
            })
        },
        selectCompanyConfirm(e) {
            this.setData({
                'contractInfo.part_b_id': e.detail.value.id,
                'contractInfo.part_b_name': e.detail.value.head,
                'contractInfo.bank_account_name': e.detail.value.head,
                'contractInfo.bank_name': e.detail.value.bank,
                'contractInfo.bank_num': e.detail.value.bank_card_num
            })
        },
        showCalendar(e) {
            if (!this.properties.disabled && !this.properties.readonly) {
                this.setData({
                    type: e.target.dataset.type,
                    calendarShow: true,
                    payIndex: e.target.dataset.index !== undefined ? e.target.dataset.index : -1
                })
            }
        },
        onCalendarConfirm(e) {
            if (this.data.type === 1) {
                this.setData({
                    'contractInfo.sign_date': util.formatDate(e.detail),
                    calendarShow: false,
                    type: 1
                })
            } else {
                let key = 'contractInfo.payDetailList[' + this.data.payIndex + '].pay_time'
                this.setData({
                    [key]: util.formatDate(e.detail),
                    calendarShow: false,
                    type: 1,
                    payIndex: -1
                })
            }
        },
        onCalendarClose() {
            this.setData({
                calendarShow: false,
                type: 1,
                payIndex: -1
            })
        },
        showMediaTypePopup(e) {
            this.setData({
                selectMediaTypeShow: true,
                tmpIndex: e.target.dataset.index,
                showPopupType: e.target.dataset.type
            })
        },
        // 根据分类（1：概况，2：换画, 3:付款）、类型（1：自有、2：代理）、索引，生成对应key值
        _getMTKeyByIndexAndType(dataset) {
            const {
                cate,
                type,
                index
            } = dataset;
            let basic = '';
            let id_key = '';
            let name_key = '';
            let spec_key = '';
            if (cate == 1) {
                // 概况
                if (type == 1) {
                    // 自有资源
                    basic = 'mediaDetailList';
                }
                if (type == 2) {
                    // 代理资源
                    basic = 'proxyMediaDetailList';
                }
                if (index !== undefined) {
                    spec_key = 'contractInfo.' + basic + '[' + index + '].media_type_spec_id';
                }
            }
            if (cate == 2) {
                // 更换画面
                if (type == 1) {
                    basic = 'contractMediaReplacePriceList';
                }
                if (type == 2) {
                    basic = 'contractProxyMediaReplacePriceList';
                }
            }
            if (cate == 3) {
                basic = 'payDetailList';
            }
            if (index !== undefined) {
                id_key = 'contractInfo.' + basic + '[' + index + '].media_type_id'
                name_key = 'contractInfo.' + basic + '[' + index + '].media_type_name'
            }
            return {
                basic,
                id_key,
                name_key,
                spec_key
            }
        },
        selectMediaTypeConfirm({
                                   currentTarget: {
                                       dataset
                                   },
                                   detail: {
                                       value: {
                                           id,
                                           name
                                       }
                                   }
                               }) {
            const that = this
            const {
                id_key,
                name_key,
                spec_key
            } = that._getMTKeyByIndexAndType(dataset);
            if (spec_key !== '') {
                that.setData({
                    [spec_key]: null,
                })
            }
            that.setData({
                [id_key]: id,
                [name_key]: name
            })
        },
        selectMediaTypeCancel() {
            this.setData({
                selectMediaTypeShow: false,
                tmpIndex: -1,
                showPopupType: 1
            })
        },
        showBeginDate() {

        },
        showMediaTypeSpecPopup(e) {
            var mediaTypeId = this.data.contractInfo.mediaDetailList[e.target.dataset.index].media_type_id;
            if (mediaTypeId === null) {
                Toast.fail('请先选择媒体类型')
                return
            }
            this.setData({
                selectMediaTypeSpecShow: true,
                tmpIndex: e.target.dataset.index,
            })
            this.getSpecList(mediaTypeId)
        },
        selectMediaTypeSpecShow({
                                    currentTarget: {
                                        dataset
                                    }
                                }) {
            const that = this
            const {
                basic
            } = that._getMTKeyByIndexAndType(dataset);
            const mediaTypeId = this.data.contractInfo[basic][dataset.index].media_type_id;
            //console.log('mediaTypeId', mediaTypeId)
            if (!mediaTypeId) {
                Toast.fail('请先选择媒体类型')
            } else {
                that.getSpecList(mediaTypeId)
            }
        },
        selectMediaTypeSpecConfirm({
                                       currentTarget: {
                                           dataset
                                       },
                                       detail: {
                                           value: {
                                               id,
                                               name
                                           }
                                       }
                                   }) {
            const that = this
            const {
                spec_key
            } = that._getMTKeyByIndexAndType(dataset);
            this.setData({
                media_type_spec_arr: [],
                [spec_key]: name
            })
        },
        selectMediaTypeSpecCancel() {
            this.setData({
                selectMediaTypeSpecShow: false,
                tmpIndex: -1,
                media_type_spec_arr: []
            })
        },
        getSpecList(id) {
            const that = this
            return new Promise((resolve, reject) => {
                that.setData({
                    selectMediaTypeSpecLoading: true
                }, function () {
                    network.GET({
                        uri: app.api.mediaSpecList,
                        params: Object.assign({
                            mediaTypeId: id
                        }, this.data.params, {
                            isMock: false
                        }),
                        success(res) {
                            res.data.unshift("无")
                            that.setData({
                                media_type_spec_arr: res.data.map((item, idx) => ({
                                    id: (idx + 1),
                                    name: item
                                })),
                                selectMediaTypeSpecLoading: false
                            }, function () {
                                resolve()
                            })
                        },
                        fail(e) {
                            Toast.fail('获取规格数据失败')
                            that.setData({
                                selectMediaTypeSpecShow: false,
                                media_type_spec_arr: []
                            }, function () {
                                reject()
                            })
                        }
                    })
                })
            })
        },
        // 获取客户待选项
        async initCustomer() {
            const that = this
            await new Promise((resolve, reject) => {
                network.GET({
                    uri: app.api.customerList,
                    params: Object.assign({}, this.data.params, {
                        isMock: false
                    }),
                    success(res) {
                        that.setData({
                            customer_arr: res.data,
                            selectCustomerLoading: false
                        })
                        resolve()
                    },
                    fail(e) {
                        console.log(e)
                        reject()
                    }
                })
            })
        },
        // 获取甲方名称历史待选项
        async initPartAArr() {
            const that = this
            await new Promise((resolve, reject) => {
                network.GET({
                    uri: app.api.partAHistoryList,
                    params: Object.assign({}, that.data.params, {
                        isMock: false,
                        customerId: that.data.contractInfo.customer_id
                    }),
                    success(res) {
                        that.setData({
                            part_a_arr: res.data.map((name, idx) => {
                                return {
                                    id: (idx + 1),
                                    name
                                }
                            }),
                            selectPartALoading: false
                        })
                        resolve()
                    },
                    fail(e) {
                        reject()
                    }
                })
            })
        },
        // 获取媒体类型待选项
        async initMediaTypeArr() {
            const that = this
            await new Promise((resolve, reject) => {
                network.GET({
                    uri: app.api.allMediaTypeList,
                    params: Object.assign({}, this.data.params, {
                        isMock: false
                    }),
                    success(res) {
                        let mtObj = {};
                        (res.data || []).forEach(item => {
                            mtObj['' + item.id] = item;
                        });
                        that.setData({
                            media_type_arr: res.data,
                            media_type_obj: mtObj,
                            selectMediaTypeLoading: false
                        })
                        resolve()
                    },
                    fail(e) {
                        console.log(e)
                        reject()
                    }
                })
            })
        },
        // 获取公司待选项
        async initCompanyArr() {
            const that = this
            await new Promise((resolve, reject) => {
                network.GET({
                    uri: app.api.companyList,
                    params: Object.assign({}, this.data.params, {
                        isMock: false
                    }),
                    success(res) {
                        that.setData({
                            company_arr: res.data.map(item => (Object.assign(item, {
                                name: item.head
                            }))),
                            selectCompanyLoading: false
                        })
                        resolve()
                    },
                    fail(e) {
                        console.log(e)
                        reject()
                    }
                })
            })
        },
        // 输入框输入
        setInputValue(e) {
            const key = e.target.dataset.key;
            const value = e.detail;
            this.setData({
                [key]: value
            })
        },
        // 单选变化
        onChangeRadio(e) {
            console.log(e)
            const key = e.target.dataset.key;
            const value = e.detail;
            this.setData({
                [key]: value
            })
        },
        // 复选框变化
        onChangeCheckBox(e) {
            console.log(e)
            const key = e.target.dataset.key;
            const value = e.detail;
            this.setData({
                [key]: value
            })
        },
        async getDetail() {
            const that = this
            const id = that.properties.contractId;
            if (id != undefined && id != null && id != -1) {
                await new Promise((resolve, reject) => {
                    network.GET({
                        uri: app.api.contractDetail + '/' + that.properties.contractId,
                        params: Object.assign(this.data.params, {isMock: false}),
                        success(res) {
                            that.setData({
                                contractInfo: Object.assign({}, res.data, {
                                    dateRange: res.data.contract_begin_date + ' — ' + res.data.contract_end_date
                                })
                            })
                            that.triggerEvent('detail', res.data)
                            resolve()
                        },
                        fail(e) {
                            console.log(e)
                            reject()
                        }
                    })
                })
            }
        },

        validForm(formData) {
            // 概况-自有资源，mediaDetailList
            const validChildren11 = function () {
                const list = formData.mediaDetailList || [];
                let flag = true;
                (list || []).forEach(item => {
                    if (!util.validEffect(item.media_type_id)) flag = false;
                    if (!util.validEffect(item.media_type_spec_id)) flag = false;
                    if (!util.validEffect(item.quantity)) flag = false;
                    if (!util.validEffect(item.duration)) flag = false;
                    if (!util.validEffect(item.amount)) flag = false;
                });
                return flag;
            };
            // 概况-代理资源，proxyMediaDetailList
            const validChildren12 = function () {
                const list = formData.proxyMediaDetailList || [];
                let flag = true;
                (list || []).forEach(item => {
                    if (!util.validEffect(item.proxy_media_type)) flag = false;
                    if (!util.validEffect(item.media_type_spec)) flag = false;
                    if (!util.validEffect(item.quantity)) flag = false;
                    if (!util.validEffect(item.duration)) flag = false;
                    if (!util.validEffect(item.amount)) flag = false;
                });
                return flag;
            };
            // 换画-自有资源，contractMediaReplacePriceList
            const validChildren21 = function () {
                const list = formData.contractMediaReplacePriceList || [];
                let flag = true;
                (list || []).forEach(item => {
                    if (!util.validEffect(item.media_type_id)) flag = false;
                    if (!util.validEffect(item.replace_price)) flag = false;
                });
                return flag;
            };
            // 换画-代理资源，contractProxyMediaReplacePriceList
            const validChildren22 = function () {
                const list = formData.contractProxyMediaReplacePriceList || [];
                let flag = true;
                (list || []).forEach(item => {
                    if (!util.validEffect(item.media_type_name)) flag = false;
                    if (!util.validEffect(item.replace_price)) flag = false;
                });
                return flag;
            };
            // 付款，payDetailList
            const validChildren31 = function () {
                const list = formData.payDetailList || [];
                let flag = true;
                (list || []).forEach(item => {
                    if (!util.validEffect(item.pay_time)) flag = false;
                    if (!util.validEffect(item.pay_amount)) flag = false;
                });
                return flag;
            };

            if (!util.validEffect(formData.customer_id)) {
                util.showToast('请选择项目');
                return false;
            }
            if (!util.validEffect(formData.part_a)) {
                util.showToast('请选择甲方');
                return false;
            }
            if (!util.validEffect(formData.part_b_id)) {
                util.showToast('请选择乙方');
                return false;
            }
            if (!util.validEffect(formData.contract_begin_date) || !util.validEffect(formData.contract_end_date)) {
                util.showToast('请选择合同期限');
                return false;
            }
            if (!util.validEffect(formData.sign_date)) {
                util.showToast('请选择合同签订日期');
                return false;
            }
            if (!!formData.contain_tax && !util.validEffect(formData.tax_percent)) {
                util.showToast('请选择填写税费百分比');
                return false;
            }
            if (add(formData.pay_cash_amount, formData.displace_amount) != formData.discounted_price) {
                util.showToast('付款合计金额与合同优惠价格不一致');
                return false;
            }
            if (!validChildren11()) {
                util.showToast('请填写完整广告发布概况-自有资源，或删除无用项');
                return false;
            }
            if (!validChildren12()) {
                util.showToast('请填写完整广告发布概况-代理资源，或删除无用项');
                return false;
            }
            if (!validChildren21()) {
                util.showToast('请填写完整画面更换费用-自有资源，或删除无用项');
                return false;
            }
            if (!validChildren22()) {
                util.showToast('请填写完整画面更换费用-自有资源，或删除无用项');
                return false;
            }
            if (!validChildren31()) {
                util.showToast('请填写完整付款方式，或删除无用项');
                return false;
            }
            // 验证合同期限
            if (!this.data.contractInfo.contract_begin_date) {
                util.showToast('请选择合同开始时间');
                return false;
            }
            if (!this.data.contractInfo.contract_end_date) {
                util.showToast('请选择合同结束时间');
                return false;
            }
            if (new Date(this.data.contractInfo.contract_end_date).getTime() <= new Date(this.data.contractInfo.contract_begin_date)) {
                util.showToast('合同结束时间应该大于合同的开始时间');
                return false;
            }
            return true;
        },

        getFormData() {
            let data = Object.assign({}, this.data.contractInfo, {
                parent_id: this.data.contractInfo.parent_id <= 0 ? null : this.data.contractInfo.parent_id
            });
            if ('' + data.contract_num === '提交后自动生成合同编号') data.contract_num = '';
            return data;
        },

        submit() {
            const that = this
            return new Promise((resolve, reject) => {
                util.showLoading('提交中');
                network.POST({
                    uri: app.api.contractBegin,
                    params: that.getFormData(),
                    success() {
                        util.hideLoading();
                        util.showToast('提交成功');
                        resolve();
                    },
                    fail() {
                        util.hideLoading();
                        util.showToast('提交失败');
                        reject();
                    }
                })
            })
        },
        save() {
            const that = this
            return new Promise((resolve, reject) => {
                util.showLoading('保存中');
                network.POST({
                    uri: app.api.contractSave,
                    params: that.getFormData(),
                    success() {
                        util.hideLoading();
                        util.showToast('保存成功');
                        resolve();
                    },
                    fail() {
                        util.hideLoading();
                        util.showToast('保存失败');
                        reject();
                    }
                })
            })
        },
        showDatetimePicker(e) {
            // 获取选中的时间
            let date = ''
            if (this.data.contractInfo[e.target.dataset.key]) {
                date = new Date(this.data.contractInfo[e.target.dataset.key])
            } else {
                date = new Date()
            }
            this.setData({
                date_key: e.target.dataset.key,
                datetimePickerShow: true,
                currentDate: date.getTime()
            })
        },
        datePickerConfirm(e) {
            let key = 'contractInfo.' + e.target.dataset.key;
            this.setData({
                [key]: formatDate(new Date(e.detail)),
                date_key: '',
                currentDate: new Date().getTime(),
                datetimePickerShow: false
            })
        },
        datePickerCancel() {
            this.setData({
                date_key: '',
                currentDate: new Date().getTime(),
                datetimePickerShow: false
            })
        }
    },
    observers: {
        'parentId': function (parentId) {
            this.setData({
                'contractInfo.parent_id': parentId
            })
        },
        'contractInfo.mediaDetailList.**': function (mediaDetailList) {
            let sum = 0
            mediaDetailList.forEach(item => {
                if (item.amount) {
                    sum = add(sum, item.amount || 0)
                }
            })
            //console.log(sum)
            this.setData({
                'contractInfo.self_price': sum,
                'contractInfo.self_price_big': amount.amountToBigStr(sum)
            })
        },
        'contractInfo.proxyMediaDetailList.**': function (proxyMediaDetailList) {
            let sum = 0
            proxyMediaDetailList.forEach(item => {
                if (item.amount) {
                    sum = add(sum, item.amount || 0)
                }
            })
            //console.log(sum)
            this.setData({
                'contractInfo.proxy_price': sum,
                'contractInfo.proxy_price_big': amount.amountToBigStr(sum)
            })
        },
        'contractInfo.self_price': function (self_price) {
            const sum = add(self_price, this.data.contractInfo.proxy_price);
            this.setData({
                'contractInfo.discounted_price': sum,
                'contractInfo.discounted_price_big': amount.amountToBigStr(sum)
            })
        },
        'contractInfo.proxy_price': function (proxy_price) {
            const sum = add(proxy_price, this.data.contractInfo.self_price);
            this.setData({
                'contractInfo.discounted_price': sum,
                'contractInfo.discounted_price_big': amount.amountToBigStr(sum)
            })
        },

        'contractInfo.payDetailList.**': function (payDetailList) {
            let sum1 = 0,
                sum2 = 0;
            payDetailList.forEach(item => {
                if (item.pay_amount) {
                    if (item.pay_type == 1) {
                        sum1 = add(sum1, item.pay_amount || 0)
                    }
                    if (item.pay_type == 2) {
                        sum2 = add(sum2, item.pay_amount || 0)
                    }
                }
            })
            //console.log(sum)
            this.setData({
                'contractInfo.pay_cash_amount': sum1,
                'contractInfo.pay_cash_amount_big': amount.amountToBigStr(sum1),
                'contractInfo.displace_amount': sum2,
                'contractInfo.displace_amount_big': amount.amountToBigStr(sum2),
            })
        },
    }
})
